// vue.config.js
var path = require("path");
var webpack = require('webpack');
const CopywebpackPlugin = require('copy-webpack-plugin');
const isProduction = process.env.NODE_ENV === 'production';
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
// const CompressionWebpackPlugin = require('compression-webpack-plugin');
// var HtmlWebpackPlugin = require('html-webpack-plugin');
// var HtmlWebpackChangeAssetsExtensionPlugin = require('html-webpack-change-assets-extension-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
function resolve(dir){
    return path.join(__dirname,dir);
}
module.exports = {
    // lintOnSave: false, //这里禁止使用eslint-loader
    publicPath: '.',
    chainWebpack: config => {
        config.plugins.delete('preload');
        config.plugins.delete('prefetch');
        config.module.rules.delete('eslint');
        const svgRule = config.module.rule('svg');
        svgRule.uses.clear();
        svgRule.exclude.add(/node_moudles/);
        svgRule.include.add(resolve('src/assets/icon'))
        svgRule.test(/\.svg$/).use('svg-sprite-loader').loader('svg-sprite-loader').options({
            symbolId: 'path-[name]'
        })
        
        const imagesRule = config.module.rule('images')
        imagesRule.exclude.add(resolve('src/assets/icon'))
        
        config.module.rule('images').test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
    },

    // 关闭js压缩，删除以下则自动进行压缩
    // configureWebpack:{
      // optimization: {
      //   minimize: false,
      // },
    // },

    // 生产环境关闭js映射map文件
    productionSourceMap: !isProduction,

    configureWebpack: config => { //压缩较大的打包文件
      if (isProduction) { //判断是生产环境
        return smp.wrap({
          plugins: [
            // 压缩后的gzip文件不能直接引入到index.html中，暂且不使用
            // new HtmlWebpackPlugin({
            //   jsExtension: '.gz',
            // }),
            // compression-webpack-plugin需要用6.0.0版，否则报错
            // new CompressionWebpackPlugin({
            //   filename: '[path][base].gz',
            //   algorithm: 'gzip', //开启gzip
            //   test: /\.js$|\.html$|\.css/, // 匹配文件名
            //   threshold: 10240, // 对超过10k的数据压缩
            //   minRatio: 0.8,
            //   deleteOriginalAssets: false // 不删除源文件
            // }),
            // 压缩后的gzip文件不能直接引入到index.html中，暂且不使用
            // new HtmlWebpackChangeAssetsExtensionPlugin(),
            // UglifyJsPlugin不支持ES6语法，改为使用terser-webpack-plugin v4（与webpack版本对齐）
            // new UglifyJsPlugin({
            //   uglifyOptions: {
            //     output: {
            //       comments: false, // 去掉注释
            //     },
            //     warnings: false,
            //     compress:{
            //       // 若要打包生产环境输出log信息，需要将以下console相关行注掉，log输出关联设置参照log_main.js和log_render.js
            //       // 移除console相关
            //       drop_console: true,
            //       drop_debugger: true,
            //       // 移除console相关
            //       pure_funcs: ['console.log', 'console.info']
            //     },
            //     sourceMap: false,
            //   }
            // }),
            new BundleAnalyzerPlugin(
              {
                analyzerMode: 'server',
                analyzerHost: '127.0.0.1',
                analyzerPort: 8889,
                reportFilename: 'report.html',
                defaultSizes: 'parsed',
                openAnalyzer: true,
                generateStatsFile: false,
                statsFilename: 'stats.json',
                statsOptions: null,
                logLevel: 'info'
              }
            ),
          ],
          optimization: {
            // js/css压缩开关
            minimize: isProduction,
            minimizer: [
              new TerserPlugin({
                //使用多进程并发运行以提高构建速度 Boolean|Number 默认值： true
                parallel: true,
                terserOptions: {
                  compress: {
                    // 若要打包生产环境输出log信息，需要将以下console相关行注掉，log输出关联设置参照log_main.js和log_render.js
                    //移除所有console相关代码
                    drop_console: true,
                    //移除自动断点功能
                    drop_debugger: true,
                    //配置移除指定的console指令，如console.log、console.info等
                    pure_funcs: ['console.log', 'console.info'],
                  },
                  output: {
                    // 删除注释
                    comments: false,
                  },
                },
                //是否将注释剥离到单独的文件中
                extractComments: false,
                //是否生成sourceMap
                sourceMap: false,
                //是否使用缓存
                cache: true,
              }),
            ],
            // js/css切片开关
            splitChunks: {
              chunks: 'all',
              minSize: 30000, // int (in bytes)允许新拆出 chunk 的最小体积，也是异步 chunk 公共模块的强制拆分体积
              maxSize: 800000, // int (in bytes)

            },
          },
          // Webpack configuration applied to web builds and the electron renderer process
          target: "electron-renderer",
          resolve: {
            mainFields: ['main', 'browser']
          },
        })
      }else{
        return smp.wrap({
          // Webpack configuration applied to web builds and the electron renderer process
          target: "electron-renderer",
          resolve: {
            mainFields: ['main', 'browser']
          },
        })
      }
    },

    pluginOptions: {
        chainWebpack: config => {
            // config.module.rules.delete('eslint');
            config.plugin('provide').use(webpack.ProvidePlugin, [{
                $: 'jquery',
                jquery: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                introJs: ['intro.js', 'introJs'],
            }]);
        },
        electronBuilder: {
            externals: ['ffi-napi', 'ref-napi', 'ref-struct-di'], // 过滤掉不能在启动前执行的库，否则无法启动（如使用'electron-screenshots'也需要在此添加）
            chainWebpackMainProcess: (config) => {
                // Chain webpack config for electron main process only
                config.module
                    .rule('native')
                    .test(/\.node$/)
                    .use('native-ext-loader')
                    .loader('native-ext-loader')
                    .end();
                // config.externals({
                //     'electron-screenshots': 'require("electron-screenshots")'
                // });
                config.plugin('copy').use(CopywebpackPlugin, [
                    [
                        {
                            from: `${__dirname}/public/**/*`,
                            to: `${__dirname}/dist_electron`,
                        },

                    ]
                ]);
            },
            chainWebpackRendererProcess: (config) => {
                // Chain webpack config for electron renderer process only (won't be applied to web builds)
                config.module
                    .rule("vue")
                    .use("vue-loader")
                    .loader("vue-loader")
                    .tap(options => {
                        options.compilerOptions.directives = {
                            html(node, directiveMeta) {
                                (node.props || (node.props = [])).push({
                                    name: "innerHTML",
                                    value: `xss(_s(${directiveMeta.value}))`
                                });
                            }
                        };
                        return options;
                    });
            },
            nodeIntegration: true,
            contextIsolation: false,
            webSecurity: false,
            // Use this to change the entrypoint of your app's main process
            // mainProcessFile: 'src/myBackgroundFile.js',
            // Use this to change the entry point of your app's render process. default src/[main|index].[js|ts]
            // rendererProcessFile: 'src/myMainRenderFile.js',
            // Provide an array of files that, when changed, will recompile the main process and restart Electron
            // Your main process file will be added by default
            // mainProcessWatch: ['src/myFile1', 'src/myFile2'],
            // Provide a list of arguments that Electron will be launched with during "electron:serve",
            // which can be accessed from the main process (src/background.js).
            // Note that it is ignored when --debug flag is used with "electron:serve", as you must launch Electron yourself
            // Command line args (excluding --debug, --dashboard, and --headless) are passed to Electron as well
            // mainProcessArgs: ['--arg-name', 'arg-value']
            mainProcessArgs: ['--disable-background-timer-throttling', ''],
            // outputDir: 'release',
            builderOptions: {
              // 产品名称
              productName: '翼丰信',
              // 修改appId是，需要同时修改backgroud.js里面设置的appUserModelId，设置见：app.setAppUserModelId(xxx)
              appId: 'com.yf-pc-chat-yfx.chat', 
              compression: 'normal',
              artifactName: 'YFXChat-${version}-${os}-${arch}.${ext}',
              protocols: {
                  name: "wf-deep-linking",
                  schemes: ["wfc"]
              },
              mac: {
                extendInfo: {
                  NSCameraUsageDescription: "This app requires camera access to record video.",
                  NSMicrophoneUsageDescription: "This app requires microphone access to record audio."
                },
                hardenedRuntime: true,
                gatekeeperAssess: false,
                entitlements: "build/mac/entitlements.mac.plist",
                entitlementsInherit: "build/mac/entitlements.mac.plist",
                target: [
                    {
                        target:'default',
                        arch:[
                          'universal'
                        ]

                    }
                ]
              },
              linux: {
                category: "Chat",
                executableName: "翼丰信",
                target: [
                  'deb',
                  'AppImage'
                ]
              },
              win: {
                target: "nsis", 
                  extraResources:[
                      {
                        from: `${__dirname}/dist_electron/screen/YfScreen.exe`,
                        to: `./YfScreen.exe`,
                      },
                      {
                        from: `${__dirname}/dist_electron/yfscreenshot`,
                        to: `./yfscreenshot`,
                      },
                      {
                        from: `${__dirname}/dist_electron/yfiletransfer`,
                        to: `./yfiletransfer`,
                      },
                      {
                        from: `${__dirname}/dist_electron/Meeting`,
                        to: `./Meeting`,
                      },
                      {
                        from: `${__dirname}/resources/dll`,
                        to: `./dll`,
                      },
                      // {
                      //   from: `${__dirname}/resources/dll/yfscreenshot_dll/platforms`,
                      //   to: `../platforms`,
                      // },
                  ],
                requestedExecutionLevel: "asInvoker",
                icon:`${__dirname}/public/favicon.ico`
              },
              nsis: {
                // 此处安装时用（会覆盖注册表中的系统指派guid），需要与pakage.json中的guid（更新时用）相同，否则程序和功能中的版本信息不能更新
                guid: 'com.yf-pc-chat-yfx.uninstall-guid',
                // 使用include时需要关闭wraning，否则打包时会报错
                warningsAsErrors: false,
                include: 'scripts/checkEnv.nsh',
                oneClick: false,
                allowToChangeInstallationDirectory: true,
                artifactName: 'YFXChat-${version}-${os}-${arch}-setup.${ext}',
                deleteAppDataOnUninstall: true,
                // 如果oneClickis false和perMachineis true：无安装模式安装程序页面，请始终按机器安装
                // 如果oneClick是false和perMachine是false（默认）：安装模式安装程序页面
                perMachine: true,
                createDesktopShortcut: 'always',
                createStartMenuShortcut: true,
                // differentialPackage: true,
                shortcutName: "翼丰信",
                uninstallDisplayName: "翼丰信",
                // 修改exe属性中的语言为中文，默认为英文
                language: '2052',
              },
              publish: {
                provider: 'generic',
                // 安装包存储路径
                // 本地测试用
                // url: 'http://localhost:5000/',
                // 下面必须要lasted.yml、full-win.json文件和需要更新的exe文件（上线时需要修改为真实下载路径）
                // minio测试用
                url: 'http://xxxxxx.yyyyyy.com/update/',
                // Release用（上线时启用）
                // url: 'https://xxxx.bbb.com/im-client/pc/update/',
              },
              // 获取增量更新包
              afterAllArtifactBuild: '.electron-delta.js',
              // 解决安装时不显示安装详细问题
              beforePack: './scripts/beforePack.js',
              // 版本发布信息（用于更新前预览）
              releaseInfo: {
                releaseNotesFile: "public/release-notes.md"
              },
            },
            // preload: 'src/preload.js',  //make sure you have this line added
            // 多个preload时
            preload: { preload: 'src/preload.js', preload_browser: 'src/preload_browser.js' },
        }
    },
    // change start up port and cors setting
    devServer: {
      open: false,
      host: 'localhost',
      port: 8080,
      https: false,
      hotOnly: false,
      disableHostCheck: true,
      transportMode: 'ws',
      injectClient: false,
      //以上的ip和端口是我们本机的;下面为需要跨域的
      proxy: {  //配置跨域

          '/api2': {
              target: 'http://111.211.1.11:31111',  //这里后台的地址模拟的;应该填写你们真实的后台接口
              ws: true,
              changOrigin: true,  //允许跨域
              pathRewrite: {
                  '^/api2': ''  //请求的时候使用这个api就可以
              }
          },
          '/api3': {
              target: 'http://11.111.111.11:1111',  //这里后台的地址模拟的;应该填写你们真实的后台接口
              ws: true,
              changOrigin: true,  //允许跨域
              pathRewrite: {
                  '^/api3': ''  //请求的时候使用这个api就可以
              }
          },
          '/api': {
              target: 'http://111.211.1.11:32222',  //这里后台的地址模拟的;应该填写你们真实的后台接口
              ws: true,
              changOrigin: true,  //允许跨域
              pathRewrite: {
                  '^/api': ''  //请求的时候使用这个api就可以
              }
          }
      }
   },
}
